package sys

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
	"net/http"
	"ruoyi-hello/app/sys/controller"
	"ruoyi-hello/common"
	"ruoyi-hello/logs"
	"ruoyi-hello/utils"
	"ruoyi-hello/utils/R"
	"ruoyi-hello/utils/error"
)

func InitRoutes() *gin.Engine {

	context := gin.Default()
	context.Use(logs.Logger())
	context.GET("/index", controller.IndexHandler)
	context.POST("/login", controller.LoginHandler)

	v1 := context.Group("/")
	auth := v1.Group("")
	auth.Use(JWTAuthMiddleware())
	auth.GET("/getInfo", controller.GetLoginUserInfoHandler)
	return context
}

func JWTAuthMiddleware() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		var token = ctx.GetHeader(common.HeaderSignToken)
		if utils.IsEmptyString(token) {
			ctx.JSON(http.StatusOK, R.ReturnFail(error.BusstionError{Code: http.StatusBadRequest, Msg: "请先登录再访问"}))
			ctx.Abort()
			return
		}
		tokenRes, err := utils.VerifyToken(token)
		if err != nil {
			ctx.JSON(http.StatusOK, R.ReturnFail(error.BusstionError{Code: http.StatusBadRequest, Msg: "请从新登录"}))
			ctx.Abort()
			return
		}
		userId := tokenRes.Claims.(jwt.MapClaims)["user_id"]
		deptId := tokenRes.Claims.(jwt.MapClaims)["dept_id"]
		ctx.Set(common.USERID, userId)
		ctx.Set(common.DEPTID, deptId)
		ctx.Next()
	}
}
